const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 获取实时数据
router.get('/', async (req, res) => {
  console.log('Accessing sensor data endpoint');
  try {
    const query = `
      SELECT 
        id,
        name,
        value,
        DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') as create_time,
        status,
        conn_state
      FROM soil_sensor
      ORDER BY create_time DESC
    `;
    console.log('Executing query:', query);
    const [rows] = await db.query(query);
    console.log(`Found ${rows.length} sensor records`);
    res.json(rows || []);
  } catch (error) {
    console.error('获取传感器数据失败:', error);
    res.status(500).json({ message: '获取传感器数据失败', error: error.message });
  }
});

// 获取历史数据 - 统一处理所有类型
router.get('/:type/history', async (req, res) => {
  console.log('Accessing sensor history endpoint');
  try {
    const { type } = req.params;
    const { startTime, endTime } = req.query;
    
    const query = `
      SELECT 
        id,
        name,
        value,
        DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') as timestamp,
        status,
        conn_state
      FROM soil_sensor
      WHERE name LIKE ? 
      AND create_time BETWEEN ? AND ?
      ORDER BY create_time ASC
    `;
    
    const namePattern = `%${type}%`;
    const [rows] = await db.query(query, [namePattern, startTime || new Date(Date.now() - 24*60*60*1000), endTime || new Date()]);
    
    res.json(rows || []);
  } catch (error) {
    console.error('获取历史数据失败:', error);
    res.status(500).json({ message: '获取历史数据失败', error: error.message });
  }
});

module.exports = router; 